export function queryString(keyValue) {
  var search = location.search.replace('?', '');

  // ads=asds&aaa=31321

  var list = search.split('&');

  // ["adsaaa=aaaasd","aaa=31aaa321"]

  list = list.map((content) => {
    var key = content.split('=')[0];
    var value = content.split('=')[1];
    return { key, value }
  })

  // [["adsaaa", "aaaasd"], ["aaa", "31aaa321"]]
  // [{key:"adsaaa", value: "aaaasd"}, ["aaa", "31aaa321"]]

  // console.log(list);

  var [obj] = list.filter(({ key }) => key === keyValue);

  // if (obj) {
  //   return obj.value;
  // }

  return obj ? obj.value : '';
}

// ajax  
// function ajax(url, fn) {
//   var xhr = new XMLHttpRequest();
//   xhr.open('get', url);
//   xhr.send();
//   xhr.onreadystatechange = function () {
//     if (xhr.readyState == 4 && xhr.status == 200) {
//       var data = JSON.parse(xhr.responseText);
//       // console.log(data);
//       // return data;
//       // setTimeout(() => {
//       fn(data);
//       // }, 100000);
//     }
//   }
//   // return undefined;
// }

export function ajax({ path, success, data = {}, type = 'get', dataType = 'json' }) {
  // const { path, success, data = {}, type = 'get', dataType = 'json' } = options;
  var params = '';
  for (var key in data) {
    params += `${key}=${data[key]}&`;
  }
  params = params.substring(0, params.length - 1);
  var xhr = new XMLHttpRequest();
  if (type.toLowerCase() === 'post') {
    xhr.open(type, path);
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    xhr.send(params);
  } else {
    xhr.open(type, `${path}?${params}`);
    xhr.send();
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      var data = xhr.responseText;
      if (dataType === 'json') {
        try {
        data = JSON.parse(data);
        } catch (e) {
          console.log(e);
        }   // 异常捕获
      }
      success && success(data);
    }
  }
}

// 设置cookie
export function setCookie(name, content, iDay = 7) {
  var date = new Date();
  date.setDate(date.getDate() + iDay);
  date.setHours(date.getHours() - 8);
  document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(content)};path=/;expires=${date}`
}
// 删除cookie
export function removeCookie(name) {
  setCookie(name, '', -1);
}
// 获取cookie对象
export function getAllCookie() {
  var cookie = document.cookie;
  var list = cookie.split('; ');
  return list.reduce(function (total, value) {
    total[value.split('=')[0]] = value.split('=')[1]
    return total;
  }, {});
}
// 获取特定的cookie
export function getCookie(name) {
  return getAllCookie()[encodeURIComponent(name)] ? decodeURIComponent(getAllCookie()[encodeURIComponent(name)]) : '';
}